package com.xs.shop.marketing.service.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xs.shop.common.exceptions.BusinessException;
import com.xs.shop.common.exceptions.enums.Resp;
import com.xs.shop.marketing.model.entity.Coupon;
import com.xs.shop.marketing.model.entity.Participation;
import com.xs.shop.marketing.service.handlers.BaseContextHandler;
import com.xs.shop.marketing.service.mapper.CouponMapper;
import com.xs.shop.marketing.service.mapper.ParticipationMapper;
import com.xs.shop.marketing.service.service.CouponService;
import com.xs.shop.marketing.service.service.ParticipationService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xs
 * @since 2025-07-16
 */
@Service
@Slf4j
public class ParticipationServiceImpl extends ServiceImpl<ParticipationMapper, Participation> implements ParticipationService {

    @Resource
    private CouponMapper couponMapper;
    @Resource
    private CouponService couponService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Participation addParticipation(Participation participation) {
        // 设置默认值
        if (participation.getStatus() == null) {
            participation.setStatus(0); // 默认参与中
        }
        participation.setCreatedAt(LocalDateTime.now());
        participation.setUpdatedAt(LocalDateTime.now());
        Long adminId = BaseContextHandler.get();
        if (adminId != null) {
            participation.setCreatedBy(adminId);
            participation.setUpdatedBy(adminId);
        }
        this.save(participation);
        return participation;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteParticipation(Long id) {
        if (id == null) {
            throw new BusinessException(Resp.INVALID_PARAM);
        }
        return this.removeById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Participation updateParticipation(Participation participation) {
        if (participation == null || participation.getId() == null) {
            throw new BusinessException(Resp.INVALID_PARAM);
        }
        participation.setUpdatedAt(LocalDateTime.now());
        participation.setUpdatedBy(BaseContextHandler.get());
        this.updateById(participation);
        return participation;
    }

    @Override
    public Participation getParticipationById(Long id) {
        if (id == null) {
            throw new BusinessException(Resp.INVALID_PARAM);
        }
        return this.getById(id);
    }

    @Override
    public Page<Participation> pageParticipation(Integer current, Integer pageSize,
                                               Long activityId, Long memberId, Long couponId,
                                               Integer status) {
        LambdaQueryWrapper<Participation> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(activityId != null, Participation::getActivityId, activityId)
                .eq(memberId != null, Participation::getMemberId, memberId)
                .eq(couponId != null, Participation::getCouponId, couponId)
                .eq(status != null, Participation::getStatus, status);

        // 按创建时间倒序
        queryWrapper.orderByDesc(Participation::getCreatedAt);

        return this.page(new Page<>(current, pageSize), queryWrapper);
    }

    @Override
    public Integer userParticipateActivityAndGetCoupon(Long activityId, Long couponId) {
        Long memberId = BaseContextHandler.get();
        if(memberId == null){
            throw new BusinessException(Resp.INVALID_PARAM);
        }
        // 用户参与活动，产生参与记录
        Participation participation = new Participation();
        participation.setActivityId(activityId);
        participation.setMemberId(memberId);
        participation.setCouponId(couponId);
        participation.setStatus(0);
        participation.setCreatedAt(LocalDateTime.now());
        participation.setUpdatedAt(LocalDateTime.now());
        this.save(participation);
        log.info("participation:{}",participation);
        // 用户参与活动，为用户发放优惠券
        Coupon coupon = couponService.getCouponByCouponId(couponId);
        // 在可用日期范围内 status为0；否则status为3
        Integer status;
        if(LocalDateTime.now().isAfter(coupon.getStartTime()) && LocalDateTime.now().isBefore(coupon.getEndTime())){
            status = 0;
        }else if(LocalDateTime.now().isAfter(coupon.getEndTime())){
            status = 2;
        }else{
            status = 3;
        }
        Integer res = couponMapper.giveMemberCoupon(memberId, couponId, activityId, status);
        return res;
    }
}

